package com.ysm.smfu.view.popu;

import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.RelativeLayout;
import android.widget.ToggleButton;

import com.ysm.smfu.R;
import com.ysm.smfu.bean.KeyValueBean;

import java.util.ArrayList;
import java.util.List;

public class ExpandPopTabView extends LinearLayout implements OnDismissListener {
    private ArrayList<RelativeLayout> mViewLists = new ArrayList<RelativeLayout>();
    private ToggleButton mSelectedToggleBtn;
    private PopupWindow mPopupWindow;
    private Context mContext;
    private int mDisplayWidth;
    private int mDisplayHeight;
    private int mSelectPosition;
    private int mTabPostion = -1; //记录TAB页号
    private int mToggleBtnBackground;
    private int mToggleBtnBackgroundColor;
    private int mToggleTextColor;
    private int mPopViewBackgroundColor;
    private float mToggleTextSize;
    private int height;
    private OnCallBackAndData onCallBackAndData;

    public ExpandPopTabView(Context context) {
        super(context);
        init(context, null);
    }

    public ExpandPopTabView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        TypedArray a = null;
        try {
            a = context.obtainStyledAttributes(attrs, R.styleable.ExpandPopTabView);
            mToggleBtnBackground = a.getResourceId(R.styleable.ExpandPopTabView_tab_toggle_btn_bg, -1);
            mToggleBtnBackgroundColor = a.getColor(R.styleable.ExpandPopTabView_tab_toggle_btn_color, -1);
            mToggleTextColor = a.getColor(R.styleable.ExpandPopTabView_tab_toggle_btn_font_color, -1);
            mPopViewBackgroundColor = a.getColor(R.styleable.ExpandPopTabView_tab_pop_bg_color, -1);
            mToggleTextSize = a.getDimension(R.styleable.ExpandPopTabView_tab_toggle_btn_font_size, -1);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (a != null) {
                a.recycle();
            }
        }
        mContext = context;
        mDisplayWidth = ((Activity) mContext).getWindowManager().getDefaultDisplay().getWidth();
        mDisplayHeight = ((Activity) mContext).getWindowManager().getDefaultDisplay().getHeight();
        setOrientation(LinearLayout.HORIZONTAL);
    }

    //    因为取反之后第一次为true，所以初始化为false
    boolean isRed = false;

    @Override
    public void onDismiss() {
        if (isNeedLimit) {
            if (!isClick && mSelectedToggleBtn != null) {
                mSelectedToggleBtn.setChecked(false);
                mSelectedToggleBtn.setTextColor(getResources().getColor(R.color.black));
                mSelectedToggleBtn = null;
                isRed = false;
            }
            isClick = false;
        } else {
            if (mSelectedToggleBtn != null) {
                mSelectedToggleBtn.setTextColor(getResources().getColor(R.color.black));
                isRed = false;
            }
            isNeedLimit = false;
        }
        mPopupWindow.setOnDismissListener(null);
    }

    /**
     * 添加toggleButton，用于初显示
     */
    public void addToggleButton(int num, String[] str) {
        for (int i = 0; i < num; i++) {
            ToggleButton tButton = (ToggleButton) LayoutInflater.from(mContext).inflate(R.layout.expand_tab_toggle_button, this, false);
            if (mToggleBtnBackground != -1) {
                tButton.setBackgroundResource(mToggleBtnBackground);
            }
            if (mToggleBtnBackgroundColor != -1) {
                tButton.setBackgroundColor(mToggleBtnBackgroundColor);
            }
            if (mToggleTextColor != -1) {
                tButton.setTextColor(mToggleTextColor);
            }
            if (mToggleTextSize != -1) {
                tButton.setTextSize(mToggleTextSize);
            }
            tButton.setText(str[i]);
            addView(tButton);
        }
    }

    boolean isClick;

    public void addItemToExpandTab(int position, String tabTitle, final ViewGroup tabItemView) {
        ToggleButton tButton = (ToggleButton) getChildAt(position);
        tButton.setText(tabTitle);
        tButton.setTag(++mTabPostion);
        tButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                ToggleButton tButton = (ToggleButton) view;
//               第一次点击
                if (mSelectedToggleBtn == null) {
                    tButton.setTextColor(getResources().getColor(R.color.red));
                    isRed = true;
                } else if (mSelectedToggleBtn != null && mSelectedToggleBtn != tButton) {
                    isClick = true;
                    mSelectedToggleBtn.setChecked(false);
                    tButton.setTextColor(getResources().getColor(R.color.red));
                    isRed = true;
                    mSelectedToggleBtn.setTextColor(getResources().getColor(R.color.black));
                } else if (mSelectedToggleBtn != null && mSelectedToggleBtn == tButton) {
                    if (isRed) {
                        tButton.setTextColor(getResources().getColor(R.color.black));
                        isRed = false;
                    } else if (tButton.isChecked()) {
                        tButton.setTextColor(getResources().getColor(R.color.red));
                        isRed = true;
                    }
                }
                mSelectedToggleBtn = tButton;
                mSelectPosition = (Integer) mSelectedToggleBtn.getTag();
                expandPopView();
            }
        });

        RelativeLayout popContainerView = new RelativeLayout(mContext);

        if (mPopViewBackgroundColor != -1) {
            popContainerView.setBackgroundColor(mPopViewBackgroundColor);
        } else {
            popContainerView.setBackgroundColor(Color.parseColor("#a0000000"));
        }
        RelativeLayout.LayoutParams rl = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, (int) (mDisplayHeight * 0.7));
        popContainerView.addView(tabItemView, rl);
        popContainerView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                onExpandPopView();
            }
        });
        mViewLists.add(popContainerView);
    }

    public void setToggleButtonText(String tabTitle) {
        ToggleButton toggleButton = (ToggleButton) getChildAt(mSelectPosition);
        toggleButton.setText(tabTitle);
    }

    boolean isNeedLimit;

    private void expandPopView() {
        if (mPopupWindow == null) {
            mPopupWindow = new PopupWindow(mViewLists.get(mSelectPosition), mDisplayWidth, (int) (mDisplayHeight - height - mDisplayHeight * 0.055));
            mPopupWindow.setAnimationStyle(R.style.PopupWindowAnimation);
            mPopupWindow.setFocusable(false);
            mPopupWindow.setOutsideTouchable(true);
        }

        if (mSelectedToggleBtn.isChecked()) {
            if (!mPopupWindow.isShowing()) {//两个按钮切换时
                showPopView();
            } else {
                isNeedLimit = true;
                mPopupWindow.dismiss();
//                showPopView();
            }
        } else {//同一个按钮
            if (mPopupWindow.isShowing()) {
                mPopupWindow.dismiss();
            }
        }
        mPopupWindow.setOnDismissListener(this);
    }

    /**
     * 如果菜单成展开状态，则让菜单收回去
     * 注：Activty 销毁时 如果对话框没有关闭刚关闭
     */
    public boolean onExpandPopView() {
        if (mPopupWindow != null && mPopupWindow.isShowing()) {
            mPopupWindow.dismiss();
            if (mSelectedToggleBtn != null) {
                mSelectedToggleBtn.setChecked(false);
            }
            return true;
        } else {
            return false;
        }
    }

    /**
     * 通过其他类调用隐藏
     */
    public void onDismissForOther() {
        if (mSelectedToggleBtn != null) {
            mSelectedToggleBtn.setChecked(false);
            mSelectedToggleBtn.setTextColor(getResources().getColor(R.color.black));
            mSelectedToggleBtn = null;
        }
        if (mPopupWindow != null && mPopupWindow.isShowing())
            mPopupWindow.dismiss();
    }

    public void showPopView() {
        if (mPopupWindow.getContentView() != mViewLists.get(mSelectPosition)) {
            mPopupWindow.setContentView(mViewLists.get(mSelectPosition));
        }
        mPopupWindow.showAsDropDown(this, 0, 0);
    }

    /**
     * 设置popup顶部高度
     */
    public void setTopBarHeight(int height) {
        this.height = height;
    }

    /**
     * 向智能排序条件中添加条目
     *
     * @param lists
     * @param defaultSelect
     * @param defaultShowText
     */
    public void addItemOne(List<KeyValueBean> lists, String defaultSelect, String defaultShowText) {
        PopOneListView_Text popOneListView = new PopOneListView_Text(getContext());
        popOneListView.setDefaultSelectByValue(defaultSelect);
        //popViewOne.setDefaultSelectByKey(defaultSelect);
        popOneListView.setCallBackAndData(lists, this, new PopOneListView_Text.OnSelectListener() {
            @Override
            public void getValue(String key, String value) {
                Log.e("tag", "key :" + key + " ,value :" + value);
                if (onCallBackAndData != null)
                    onCallBackAndData.getValueOne(key, value);
            }
        });
        addItemToExpandTab(1, defaultShowText, popOneListView);
    }

    /**
     * 向全部排序条件中添加条目
     *
     * @param lists
     * @param defaultSelect
     * @param defaultShowText
     */
    public void addItemThree(List<KeyValueBean> lists, String defaultSelect, String defaultShowText) {
        PopListView_All popThreeListView = new PopListView_All(getContext());
        popThreeListView.setDefaultSelectByValue(defaultSelect);
        //popViewOne.setDefaultSelectByKey(defaultSelect);
        popThreeListView.setCallBackAndData(lists, this, new PopListView_All.OnSelectListener() {
            @Override
            public void getValue(String key, String value) {
                Log.e("tag", "key :" + key + " ,value :" + value);
                if (onCallBackAndData != null)
                    onCallBackAndData.getValueThree(key, value);
            }
        });
        addItemToExpandTab(0, defaultShowText, popThreeListView);
    }

    /**
     * 向筛选排序条件中添加条目
     *
     * @param defaultShowText
     */
    public void addItemFour(String defaultShowText) {
        PopFourListView popFourListView = new PopFourListView(getContext());
//        popThreeListView.setDefaultSelectByValue(defaultSelect);
        //popViewOne.setDefaultSelectByKey(defaultSelect);
        popFourListView.setCallBackAndData(this, new PopFourListView.OnSelectListener() {
            @Override
            public void getValue(boolean isFreeuse, boolean isUseHoliday, int lunTime, int lunServe, int lunCount) {
                if (onCallBackAndData != null)
                    onCallBackAndData.getValueFour(isFreeuse, isUseHoliday, lunTime, lunServe, lunCount);
            }
        });
        popFourListView.setExpandPopTabView(this);
        addItemToExpandTab(2, defaultShowText, popFourListView);
    }

    /**
     * 向附近条件中添加条目
     * @param parentLists
     * @param childrenListLists
     * @param defaultParentSelect
     * @param defaultChildSelect
     * @param defaultShowText
     */
    public void addItemTwo(List<KeyValueBean> parentLists,
                           List<ArrayList<KeyValueBean>> childrenListLists, String defaultParentSelect, String defaultChildSelect, String defaultShowText) {
        PopTwoListView_TwoListView popTwoListView = new PopTwoListView_TwoListView(getContext());
        popTwoListView.setDefaultSelectByValue(defaultParentSelect, defaultChildSelect);
        //distanceView.setDefaultSelectByKey(defaultParent, defaultChild);
        popTwoListView.setCallBackAndData(this, parentLists, childrenListLists, new PopTwoListView_TwoListView.OnSelectListener() {
            @Override
            public void getValue(String showText, String parentKey, String childrenKey) {
                Log.e("tag", "showText :" + showText + " ,parentKey :" + parentKey + " ,childrenKey :" + childrenKey);
                if (onCallBackAndData != null)
                    onCallBackAndData.getValueTwo(parentKey, childrenKey);
            }
        });
        addItemToExpandTab(3, defaultShowText, popTwoListView);
    }

    public interface OnCallBackAndData {
        void getValueOne(String key, String value);

        void getValueTwo(String key, String value);

        void getValueThree(String key, String value);

        void getValueFour(boolean isFreeuse, boolean isUseHoliday, int lunTime, int lunServe, int lunCount);
    }
}
